import { creepRuleNameEnum, taskType } from "../../../enum"
import { creepNameToObj, objIDToObj, roomOwner } from "../../../tools/baseTools"
import { updateStructureCreepList } from "../../../tools/memoryData"
import { changeCreepRule, creepGetSource, creepGetTask, creepIsNotRuning, creepMoveExtesion, deleteCreepToTargetCreepList, isTargetPos, pushCreepToTargetCreepList } from "../../../tools/tools/creepTool"
import structureTool from "../../../tools/tools/structureTool"
import eventManager from "../../event/eventManager"
import { eventMap } from "../../event/eventMap"

export default {
    /**
     * 
     * @param {Creep} creep 
     */
    run: function (creep) {
        let creepMemory = creep.memory
        if (creepMemory.state.isWorking) {
            if (!creep.pos.isEqualTo(creepMemory.targetPos.x, creepMemory.targetPos.y)) {
                creep.say('正在前往container')
                creep.moveTo(creepMemory.targetPos.x, creepMemory.targetPos.y, { visualizePathStyle: {} })
            } else {
                ruleHarvesterWorking(creep)
            }
        } else {
            creep.say(`准备挖矿`)
            ruleHarvesterPrepare(creep)
        }
    }
}

/**采集者的准备逻辑
 * 
 * @param {Creep} creep 
 */
function ruleHarvesterPrepare(creep) {
    /**先寻找合适的矿点
     * 1. 矿点要存在container,且container未被占用
     * 2. 矿点要根据挂载的Harvester数量进行排序，升序排列
     */
    let room = creep.room
    if (!roomOwner(room) > 1) return     // 不是我的房间则跳过;TODO：后续添加攻占逻辑
    let sourceList = []
    Object.keys(room.memory['structure']['source']).map(id => {
        let sourceMemory = room.memory['structure']['source'][id]
        let containerList = sourceMemory['collectPoint'].filter(point => point.type == STRUCTURE_CONTAINER)
        let containersMemory = room.memory['structure'][STRUCTURE_CONTAINER]
        let container = containerList.filter(obj => {
            // 更新指定建筑挂载的creep的目标是否为指定建筑
            let holderHarvester = false
            containersMemory[obj.id].creeps = containersMemory[obj.id].creeps.filter(creepName => {
                if (holderHarvester) return true    // 发现container中挂载了Harvester，之后的都可以保留
                let creepMemory = Memory.creeps[creepName]
                if (creepMemory.rule == creepRuleNameEnum.ruleHarvester) {
                    if (creepMemory.params['container'] != obj.id) return false
                    holderHarvester = true
                }
            })
            if (!holderHarvester) return true
        })[0]
        if (!container) return
        sourceList.push({ 'id': id, 'container': container.id, 'containerPos': { 'x': container.x, 'y': container.y, 'roomName': room.name }, 'creepAmount': sourceMemory.creeps.length })
    })
    if (sourceList.length != 0) {
        let sourceDeta = sourceList.sort((a, b) => a.creepAmount - b.creepAmount)[0]
        // 获取已确认前往资源点的extension参数
        let sourceMemory = room.memory['structure']['source'][sourceDeta.id]
        let extensionList = sourceMemory['extensionPoint'].filter(point => point.type == STRUCTURE_EXTENSION)
        sourceDeta['extension'] = []
        if (extensionList.length != 0) extensionList.map(obj => sourceDeta['extension'].push(obj.id))
        // 将参数录入creep的内存中
        creep.memory.state.isWorking = true
        creepIsNotRuning(creep)
        creep.memory.targetID = []
        creep.memory.targetID.push(sourceDeta.id)
        creep.memory.targetPos = sourceDeta.containerPos
        creep.memory.params['extension'] = sourceDeta.extension
        creep.memory.params['container'] = sourceDeta.container

        let containersMemory = room.memory['structure'][STRUCTURE_CONTAINER][sourceDeta.container]
        if (!containersMemory.creeps.includes(creep.name)) containersMemory.creeps.push(creep.name) // 强制推送当前creep到目标container
    } else {
        console.log(`${creep.name}在Harvester的准备阶段没有合适的目标`);
    }
}
/**采集者的工作逻辑
 * 1. 检查附近的extension是否满载，不满载则跳过
 */
function ruleHarvesterWorking(creep) {
    creep = creepNameToObj(creep)
    let sourceObj = objIDToObj(creep.memory.targetID[0])
    // 强制推送当前creep到目标container
    let containersMemory = creep.room.memory['structure'][STRUCTURE_CONTAINER][creep.memory.params.container]
    if (!containersMemory.creeps.includes(creep.name)) containersMemory.creeps.push(creep.name)
    let resultCode = creep.harvest(sourceObj)
    // console.log(`${creep.name}执行harvest操作结果编码${resultCode}`);
    switch (resultCode) {
        case OK:
            if (creep.memory.state.isRuning) creepIsNotRuning(creep)
            if (creep.store.getFreeCapacity() == 0) {
                let extension = creep.memory.params.extension.filter(id => creep.room.memory['structure']['extension'][id].state.needEnergy)
                if (extension.length != 0) {    // 给extension填充                    
                    extension = extension[0]
                    ruleHarvesterTransferExtension(creep, extension)
                } else {
                    // 给container填充，做个计时器，减少cpu消耗吧,每30tick检查一次
                    if (!creep.memory.params.tick) creep.memory.params.tick = 0
                    if (creep.memory.params.tick < 30) {
                        creep.memory.params.tick++
                    } else {
                        let containerObj = objIDToObj(creep.memory.params.container)
                        if (containerObj.store.getFreeCapacity() == 0) creep.memory.state.isWorking = false
                    }
                }
            }
            break;
        default:
            if (creep.memory.state.isRuning) creepIsNotRuning(creep)
            console.log(creep.name + `使用repair的逻辑可能出现问题了,错误编码${resultCode}`);
            break;
    }
}

function ruleHarvesterTransferExtension(creep, obj) {
    obj = objIDToObj(obj)
    let resultCode = creep.transfer(obj, RESOURCE_ENERGY)
    // console.log(`${creep.name}执行transfer操作结果编码${resultCode}`);
    switch (resultCode) {
        case OK:
            break;
        case ERR_FULL:
            console.log(`${obj.structureType}类型的建筑` + obj.name ? obj.name : obj.id + `已经装满能量`);
            creep.room.memory['structure'][obj.structureType][obj.id].state.needEnergy = false
            break;
        case ERR_NOT_IN_RANGE:
            creep.moveTo(obj.pos)
            break;
        default:
            console.log(creep.name + `使用transfer的逻辑可能出现问题了,错误编码${resultCode}`);
            break;
    }
}

/*
export default {
    run: function (creep) {
        let isRuning = false
        creep = creepNameToObj(creep)
        if (creep.memory.state.isWorking) {
            let isTransfer = false
            if (!creep.store.getFreeCapacity()) {
                // 背包已满,检验是否存在需要填充的电池
                creep.memory.params.extension.map(id => {
                    if (isTransfer) return
                    let obj = objIDToObj(id)
                    if (obj.store.getFreeCapacity(RESOURCE_ENERGY)) {
                        isTransfer = true
                        creep.memory.params.targetExtension = id
                    }
                })
            }
            if (isTransfer) {
                // 给extension填充
                ruleHarvesterTransfer(creep)
            } else {
                // 给store填充
                isRuning = ruleHarvesterWorking(creep)
            }
        } else {
            // 准备逻辑
            ruleHarvesterPrepare(creep)
        }
    }
}
*/

// /** 准备逻辑存在三种情况
//  * 1. 有store，有extension：先填充所有extension，然后填充脚下
//  * 2. 有store，无extension：只填充脚下，脚下填充满了自检
//  * 3. 无store，有extension：没有store则转换为freeman
//  * 合计流程：填充extension=>自检=>填充脚下=>自检
//  */
// function ruleHarvesterPrepare(creep) {
//     let room = Game.rooms[creep.memory.targetPos.roomName]
//     /**获取当前房间所有矿点挂载的creep中Harvester最少的矿点，且矿点必须要存在store */
//     let targetDetaList = Object.keys(room.memory['structure']['source']).sort((a, b) => {
//         let aMemory = room.memory['structure']['source'][a]
//         let bMemory = room.memory['structure']['source'][b]
//         return getMinCreepRuleInObj(creepRuleNameEnum.ruleHarvester, aMemory) - getMinCreepRuleInObj(creepRuleNameEnum.ruleHarvester, bMemory)
//     })
//     targetDetaList = targetDetaList.map(id => { return { 'id': id } })  // 转换为对象来存储与id对应的store位置数量


//     let isOK = false
//     if (!creep.memory.params['targetID']) creep.memory.params['targetID'] = null
//     // 获取与每个矿点id对应的store位置数量
//     let collectPointList = []
//     targetDetaList.map((objDeta, index) => {
//         let targetMemory = room.memory['structure']['source'][objDeta.id]
//         let containerID = null
//         /**获取所有store点位，站位点
//          * 1. 存在点位，则存储到creep.memory.params.targetID
//          * 2. 不存在点位，则collectPoint.length==0
//          */
//         let collectPoint = targetMemory.collectPoint.filter(
//             point => {
//                 if (isOK) return false  //当存在合适的点，则跳过后续所有点
//                 let targetObj = room.lookAt(point.x, point.y)
//                 if (targetObj.some(obj => {
//                     if (obj.type == 'structure' && obj.structure.structureType == 'container') {
//                         // 还要满足container没有挂载creeps
//                         obj = obj.structure
//                         let isAllowHarvester = false
//                         let objMemory = room.memory['structure']['container'][obj.id]
//                         if (objMemory.creeps.length == 0) isAllowHarvester = false
//                         else isAllowHarvester = objMemory.creeps.some(creepName => {
//                             if (!Game.creeps[creepName]) return false
//                             return Memory.creeps[creepName].rule == creepRuleNameEnum.ruleHarvester
//                         })
//                         // console.log(`挂载的creep数量:${objMemory.creeps.join()}`);
//                         // console.log(`${isAllowHarvester}`);
//                         // console.log(`${obj.store.getFreeCapacity()}`);
//                         if (obj.store.getFreeCapacity() != 0 && !isAllowHarvester) {
//                             creep.memory.params.targetID = obj.id
//                             containerID = obj.id  // 满足要求的containerID
//                             isOK = true
//                             return true // 告诉targetObj该点位满足存在空存储，且为container的要求
//                         }
//                     }
//                 })) return true // 告诉point该点位满足存在空存储，且为container的要求
//             }
//         )
//         if (collectPoint.length != 0) collectPointList.push({ 'id': targetDetaList[index].id, 'collectPoint': collectPoint[0], 'containerID': containerID })
//     })
//     console.log('修改后的数组' + JSON.stringify(collectPointList));
//     if (collectPointList.length == 0) {
//         console.log(`当前房间${room.name}不存在空余工位的能源矿`);
//         // changeCreepRule(creep)
//         return
//     }
//     let targetMemory = room.memory['structure']['source'][collectPointList[0].id]
//     /**获取所有extension点位 */
//     creep.memory.params['extension'] = []
//     if (!creep.memory.params['extension']) creep.memory.params['extension'] = []
//     targetMemory.extensionPoint.map(point => {
//         let targetObj = room.lookAt(point.x, point.y)
//         targetObj.some(obj => {
//             if (obj.type == 'structure' && obj.structure.structureType == 'extension') {
//                 obj = obj.structure
//                 creep.memory.params['extension'].push(obj.id)
//             }
//         })
//     })
//     console.log(`当前所有extension点位${JSON.stringify(targetMemory.extensionPoint)}`);
//     // 完成准备工作
//     if (!collectPointList[0]['collectPoint']) {
//         console.log('不存在store');
//     } else {
//         console.log('存在store');
//         creep.memory.targetID = []
//         creep.memory.targetID.push(collectPointList[0]['id'])
//         pushCreepToTargetCreepList(creep)
//         creep.memory.params.targetID = collectPointList[0]['containerID']
//         creep.memory.params.targetPos = collectPointList[0]['collectPoint']
//         creep.memory.state.isWorking = true
//     }
// }

// function ruleHarvesterWorking(creep) {
//     if (creep.memory.params.targetID) { // 资源矿存在stroe
//         if (!creep.pos.isEqualTo(creep.memory.params.targetPos.x, creep.memory.params.targetPos.y)) {
//             creep.moveTo(creep.memory.params.targetPos.x, creep.memory.params.targetPos.y)
//         }
//         let targetObj = objIDToObj(creep.memory.targetID[0])
//         let resultCode = creep.harvest(targetObj)
//         // console.log(`harvest的逻辑结果编码${resultCode}`);
//         switch (resultCode) {
//             case OK:
//                 // 检查背包的存储是否满了
//                 if (!creep.store.getFreeCapacity()) {
//                     let containerObj = objIDToObj(creep.memory.params.targetID)
//                     let containerMemory = containerObj.room.memory['structure'][containerObj.structureType][containerObj.id]
//                     if (!containerMemory.creeps.includes(creep.name)) containerMemory.creeps.push(creep.name)
//                     if (containerObj.store.getFreeCapacity() != 0) break
//                     // 添加一个判断，如果当前已经没有了可用的store，那么就保持原目标
//                     if (!creep.memory.params['checkContainer'] && getContainerListBySource(targetObj).length == 0) {
//                         creep.memory.params['checkContainer'] = true
//                         eventManager.add(`${creep.name}保持采集,间隔后重新检查container`, 30, eventMap.changHarvesterCheckContainer, { creepName: creep.name })
//                         creep.memory.state.isWorking = false
//                         // updateStructureCreepList(Game.getObjectById(creep.memory.targetID.pop()))
//                     }

//                 }
//                 // 检查脚下的存储是否满了
//                 break;
//             case ERR_NOT_IN_RANGE:
//                 break;

//             default:
//                 console.log(creep.name + `使用harvest的逻辑可能出现问题了,错误编码${resultCode}`);
//                 break;
//         }
//     } else {
//         // 资源矿不存在stroe
//         console.log(`${creep.name}不满足采集需求，切换为freeman的Rule`);
//         // changeCreepRule(creep)
//         // creep.memory.state.isWorking = false

//     }
// }

// /**给extension填充能源 */
// function ruleHarvesterTransfer(creep) {
//     let targetObj = objIDToObj(creep.memory.params.targetExtension)
//     let resultCode = creep.transfer(targetObj, RESOURCE_ENERGY)
//     switch (resultCode) {
//         case OK:

//             break;
//         case ERR_NOT_IN_RANGE:
//             creep.moveTo(targetObj.pos)
//             break;

//         default:
//             console.log(creep.name + `使用transfer的逻辑可能出现问题了,错误编码${resultCode}`);
//             break;
//     }
// }

// /**获取目标内存中挂载的对应类型creep数量 */
// function getMinCreepRuleInObj(creepRule, objMemory) {
//     let creepList = objMemory.creeps
//     if (creepList.length == 0) return 0
//     return creepList.filter(creepName => {
//         if (Memory.creeps[creepName].rule == creepRule) return true
//     }).length
// }

// /**检查source的Container */
// function getContainerListBySource(source) {
//     source = objIDToObj(source)
//     let room = source.room
//     let collectPointList = []
//     let targetMemory = room.memory['structure']['source'][source.id]
//     let containerID = null
//     /**获取所有store点位，站位点
//      * 1. 存在点位，则存储到creep.memory.params.targetID
//      * 2. 不存在点位，则collectPoint.length==0
//      */
//     let isOK = false
//     let collectPoint = []
//     collectPoint = targetMemory.collectPoint.filter(
//         point => {
//             if (isOK) return false  //当存在合适的点，则跳过后续所有点
//             let targetObj = room.lookAt(point.x, point.y)
//             if (targetObj.some(obj => {
//                 if (obj.type == 'structure' && obj.structure.structureType == 'container') {
//                     console.log('还要满足container没有挂载creeps');
//                     // 还要满足container没有挂载creeps
//                     obj = obj.structure
//                     let isAllowHarvester = false
//                     let objMemory = room.memory['structure']['container'][obj.id]
//                     if (objMemory.creeps.length == 0) isAllowHarvester = false
//                     else isAllowHarvester = objMemory.creeps.some(creepName => {
//                         if (!Memory.creeps[creepName]) return false
//                         return Memory.creeps[creepName].rule == creepRuleNameEnum.ruleHarvester
//                     })
//                     if (obj.store.getFreeCapacity() != 0 && !isAllowHarvester) {
//                         console.log('完全满足要求的container' + obj.id);
//                         containerID = obj.id  // 满足要求的containerID
//                         isOK = true
//                         return true // 告诉targetObj该点位满足存在空存储，且为container的要求
//                     }
//                 }
//             })) return true // 告诉point该点位满足存在空存储，且为container的要求
//             console.log(JSON.stringify(collectPoint));
//             if (collectPoint.length != 0) collectPointList.push({ 'id': targetDetaList[index].id, 'collectPoint': collectPoint[0], 'containerID': containerID })
//         })
//     console.log('修改后的数组' + JSON.stringify(collectPointList));
//     return collectPointList
// }